package input

import (
	"m3u8/info"
	"m3u8/util"
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
)

type Input struct {
	urlBefore string
	tsNamePattern string
	count int
	files []string
}
func (i *Input) GetCount()int{
	return i.count
}

func (i *Input) GetUrl() string {
	return i.urlBefore
}

func (i *Input) GetFiles() []string {
	return i.files
}

func (i *Input) GetM3u8Name() string{
	urlArr:=strings.Split(i.urlBefore,"/")
	file:=urlArr[len(urlArr)-1]
	return strings.Split(file,".")[0]
}

func (i *Input) Dir() string {
	return "E:/"
}

func (i *Input) GetTsNamePattern() string {
	return i.tsNamePattern
}

func (i *Input) Parse(){
	var urlBefore=flag.String("u","","url地址")
	var tsNamePattern=flag.String("p","","TS文件的匹配名")
	var count = flag.Int("c",0,"文件数量")
	flag.Parse()

	i.urlBefore=*urlBefore
	i.tsNamePattern=*tsNamePattern
	i.count=*count
	i.count++

	if *urlBefore=="" || *count==0 || *tsNamePattern=="" {
		fmt.Println("参数说明：")
		fmt.Println("-u url地址")
		fmt.Println("-p TS文件的匹配名，使用X代替数字")
		fmt.Println("-c 文件数量")
		os.Exit(1)
	}
	uri,err:=url.Parse(i.urlBefore)
	if err!=nil{
		fmt.Println("解析URL出错",err)
		os.Exit(1)
	}
	if uri.Scheme==""||uri.Host==""{
		fmt.Println("不正确的URL")
		os.Exit(1)
	}
	i.files=make([]string,i.count)
}

func (i *Input) SaveTs(index int,channel chan info.Info){
	iStr:=strconv.Itoa(index)
	filename:=strings.Replace(i.tsNamePattern,"X",iStr,-1)
	defer func() {
		i.files[index-1]=i.Dir()+filename
	}()
	curlUrl:=i.urlBefore+"/"+filename

	if util.Exists(i.Dir()+filename){
		channel<-info.Info{Num:index,Msg:filename+"已存在"}
		return
	}

	proxy := func(_ *http.Request) (*url.URL, error) {
		return url.Parse("http://127.0.0.1:8118")//根据定义Proxy func(*Request) (*url.URL, error)这里要返回url.URL
	}
	transport := &http.Transport{Proxy: proxy}

	client:=&http.Client{Transport:transport}
	request,err1:=http.NewRequest("GET",curlUrl,nil)
	if err1!=nil{
		channel<-info.Info{Num:index,Msg:err1.Error()}
		return
	}

	request.Header.Add("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36")
	request.Header.Add("Origin","http://hbo6.hboav.com")

	response,err2:=client.Do(request)
	if err2!=nil{
		channel<-info.Info{Num:index,Msg:err2.Error()}
		return
	}
	defer response.Body.Close()

	data, err3 :=ioutil.ReadAll(response.Body)
	if err3!=nil{
		channel<-info.Info{Num:index,Msg:err3.Error()}
		return
	}

	saveFilename:=i.Dir()+filename
	err4 := ioutil.WriteFile(saveFilename, data, 0777)
	if err4!=nil{
		channel<-info.Info{Num:index,Msg:err4.Error()}
		return
	}

	channel<-info.Info{Num:index,Msg:" "+filename + " success"}
}
